package com.team.est.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.team.est.dto.ModelDto;
import com.team.est.entity.Model;
import com.team.est.entity.ModelExample;
import com.team.est.mapper.ModelMapper;
import com.team.est.req.ModelReq;
import com.team.est.utils.Page;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 樊浩
 * @version 1.0
 * @description: TODO
 * @date 2021/3/6 13:45
 */
@RestController
@RequestMapping("/model/")
public class ModelServiceImpl {

 @Autowired(required = false)
 private ModelMapper modelMapper;

 //注意:在springcloud的服务提供者中如果方法传递的是对象请使用@RequestBody
 //如果@RequestBody传递参数时，浏览器无法传requestBody的参数需要使用postman进行测试
 @RequestMapping("searchModel")
 public Page<ModelDto> searchModel( ModelReq modelReq){
  //开启分页
  PageHelper.startPage(modelReq.getPageNo(),modelReq.getPageSize());
  //1.通过查询的条件进行分页查询
  ModelExample modelExample=new ModelExample();
  ModelExample.Criteria criteria=modelExample.createCriteria();
   //追加条件
  if (modelReq.getClassifyId()!=null)
     criteria.andClassifyIdEqualTo(modelReq.getClassifyId());
  if (modelReq.getBrandId()!=null)
     criteria.andBrandIdEqualTo(modelReq.getBrandId());
  if (modelReq.getModelName()!=null){
   criteria.andModelNameLike("%"+modelReq.getModelName()+"%");
  }
  List<Model> modelList=this.modelMapper.selectByExample(modelExample);
  PageInfo<Model> pageInfo=new PageInfo<>(modelList);

  //将数据库获取的结果，转化返回返回的DTO
  Page<ModelDto> modelDtoPage=new Page<ModelDto>(pageInfo.getPageNum(),pageInfo.getPageSize(), (int) pageInfo.getTotal());
  //设置总页
  modelDtoPage.setPages(pageInfo.getPages());
  //将数据的实体集合转化为商品dto的实体集合
  List<ModelDto> modelDtos=new ArrayList<ModelDto>();
  for (Model model:modelList) {
   //循环一次   一个modelDto
   ModelDto modelDto=new ModelDto(model.getId(),model.getModelName(),model.getFaceImg());
    //将dto添加到集合
   modelDtos.add(modelDto);
  }
  //设置返回数据
  modelDtoPage.setList(modelDtos);
  return modelDtoPage;
 }
}
